package com.sqlcheck.config;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户ID参数解析器
 * 自动从请求属性中提取X-User-ID并注入到控制器方法参数中
 */
@Component
public class UserIdArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 支持Long类型且参数名为userId或参数有@RequestHeader("X-User-ID")注解的参数
        return parameter.getParameterType().equals(Long.class) &&
                (parameter.getParameterName().equals("userId") ||
                        parameter.hasParameterAnnotation(org.springframework.web.bind.annotation.RequestHeader.class));
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request != null) {
            Object userId = request.getAttribute("X-User-ID");
            if (userId instanceof Long) {
                return userId;
            }
        }

        // 如果没有找到用户ID，返回null（控制器可以处理这种情况）
        return null;
    }
}